from sqlalchemy.orm import Session, joinedload
from fastapi import HTTPException
from pydantic import BaseModel
from typing import Optional
from sqlalchemy.orm import Session
from day20.models.models_score import Score
from day20.schema.schema_score import ScoreCreateSchema, ScoreResponseSchema, ScoreUpdateSchema

# 查询score表中所有信息
def score_all_info(db: Session):
    return db.query(Score).all()

# 查询指定成绩信息
def score_info_by_id(db: Session, stu_id: int, assessment_sequence: Optional[int]= None):
    if assessment_sequence != None:
        return db.query(Score).filter(Score.stu_id == stu_id, Score.assessment_sequence == assessment_sequence).all()
    return db.query(Score).filter(Score.stu_id == stu_id).all()

# 录入成绩
def score_add(db: Session, score_schema: ScoreCreateSchema):
    db_score = Score(**score_schema.dict())
    db.add(db_score)
    db.commit()
    db.refresh(db_score)
    return db_score

# 修改成绩信息
def score_update(db: Session, stu_id: int,assessment_sequence: int, score_update_schema: ScoreUpdateSchema):
    db_score = db.query(Score).filter(Score.stu_id == stu_id, Score.assessment_sequence == assessment_sequence).first()
    if not db_score:
        raise HTTPException(status_code=404, detail="学生不存在")
    update_dict = score_update_schema.dict(exclude_unset=True)

    # 仅更新传递的字段（未传递的字段不处理，保持数据库原有值）
    for key, value in update_dict.items():
        setattr(db_score, key, value)

    db.commit()
    db.refresh(db_score)
    return db_score



# 删除成绩
def score_del(db: Session, stu_id: int):
    res = db.query(Score).filter(Score.stu_id == stu_id).delete()
    db.commit()
    return res